/**
 * 
 */
package com.nars.inputStreams;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @author Student
 * 
 */
public class StudentFile {

	private String studentFile = "student.txt";
	File file = new File(studentFile);
	private RandomAccessFile raf = null;

	public StudentFile() {
		try {
			raf = new RandomAccessFile(file, "rw");
			try {
				raf.setLength(0);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void add(Student stundent) {
		try {
			raf = new RandomAccessFile(file, "rw");
			System.out.println("File Pointer: " + raf.getFilePointer());
			long length = file.length();
			System.out.println("File Length: " + length);
			raf.seek(file.length());
			System.out.println("File Pointer: " + raf.getFilePointer());
			raf.writeUTF(stundent.name);
			raf.writeInt(stundent.facultyNumber);
			raf.writeInt(stundent.course);
			raf.writeInt(stundent.score);
			System.out.println("Adding..	" + stundent.toString());

		} catch (IOException e) {
			// TODO: handle exception
		} finally {
			try {
				raf.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public String search(String name) {
		Student tempStudent = new Student();
		try {
			raf = new RandomAccessFile(studentFile, "r");
			long fileLength = file.length();
			long pointer = 0;
			if (fileLength == 0) {
				return null;
			}
			System.out.println("File Length: " + fileLength);
			raf.seek(0);
			System.out.println("File Pointer: " + raf.getFilePointer());
			while (pointer < fileLength) {
				tempStudent.name = raf.readUTF();
				System.out.println(tempStudent.name);
				tempStudent.facultyNumber = raf.readInt();
				System.out.println(tempStudent.facultyNumber);
				tempStudent.course = raf.readInt();
				System.out.println(tempStudent.course);
				tempStudent.score = raf.readInt();
				System.out.println(tempStudent.score);
				if (tempStudent.name.equals(name)) {
					System.out.println("Found!");
					break;
				}
				pointer = raf.getFilePointer();
			}

		} catch (IOException e) {
			return null;
		} finally {
			try {
				raf.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return tempStudent.toString();
	}
}
